package com.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.reggie.common.R;
import com.reggie.entity.User;
import com.reggie.service.UserService;
import com.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService userService;


    @Autowired
    RedisTemplate redisTemplate;

    @PostMapping("/sendMsg")
    public R<String> sendMsg(String phone) {
        int integer = ValidateCodeUtils.generateValidateCode(6);

        redisTemplate.opsForValue().set(phone,integer, 5, TimeUnit.MINUTES);
        return R.success("成功");
    }

    @PostMapping("/login")
    public R<User> login(@RequestBody Map map, HttpServletRequest httpServletRequest) {
        // 获取手机号
        String phone = map.get("phone").toString();
        // 获取验证码
        if(map.get("code") != null) {
            String code = map.get("code").toString();
        }

        Object o = redisTemplate.opsForValue().get(phone);
        System.out.println(o);
        // 如果验证成功
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getPhone, phone);
        User user = userService.getOne(lambdaQueryWrapper);
        if(user == null) {
            user = new User();
            user.setPhone(phone);
            user.setStatus(1);
            userService.save(user);
        }
        // 添加到session中
        log.info("user", user.getId());
        httpServletRequest.getSession().setAttribute("user", user.getId());
        return R.success(user);
    }
}
